//官网 https://www.npmjs.com/package/express
//导包
const express = require("express")
const app = express()
const multer = require("multer")
const path = require("path")
var md5 = require('md5');
var bodyParser = require('body-parser')
var upload = multer({ dest: path.join(__dirname, "www", "uploads/") })
app.use(express.static('www'))

const cors = require("cors")

app.use(cors())
//导入数据库依赖项
var mysql = require('mysql');
const { connect } = require("http2")
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'mymanager'
});


// app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.urlencoded({ extended: false }));

// connection.query('select * from herolist', function (error, results, fields) {
//     if (error) throw error;
//     console.log('接收到的数据是', results);
// });




//配置接口 1.新增英雄
app.post("/hero/add", upload.single("heroIcon"), (req, res) => {
    // req.body

    let { heroName, heroSkill } = req.body
    let heroIcon=''
if(req.file){
    heroIcon = 'http://127.0.0.1:8089/uploads/' + req.file.filename
 
}else{
     heroIcon=req.body.heroIconInput
}

    connection.query(`insert into herolist(heroName,heroSkill,heroIcon,isDelete) values('${heroName}','${heroSkill}','${heroIcon}','false')`, function (error, results, fields) {
        if (!error) {
            res.send({
                code: 201,
                data: '新增成功'
            })
        } else {
            res.send({
                code: 500,
                msg: '新增失败，服务器错误'
            })
        }
    });
})


//2.获取所有英雄接口
app.get("/hero/all", (req, res) => {
    connection.query(`select id,heroName,heroSkill,heroIcon from herolist where isDelete='false' order by id desc`, function (error, results, fields) {
        if (!error) {
            res.send({
                code: 201,
                data: results
            })
        } else {
            res.send({
                code: 500,
                msg: '查询失败，服务器错误'
            })
        }
    });
    
})

//3.删除英雄的接口
app.get("/hero/delete",(req,res)=>{
   let {id}= req.query
   connection.query(`update herolist set isDelete="true" where id=${id}`, function (error, results, fields) {
    if (!error) {
        res.send({
            code: 300,
            msg: '删除成功'
        })
    } else {
        res.send({
            code: 500,
            msg: '删除失败，服务器错误'
        })
    }

});
  
})

//4.获取编辑英雄接口，通过英雄id查找英雄并渲染到页面上，再使用mysql语句更新数据
app.get("/hero/getHeroById",(req,res)=>{
    let {id} = req.query
    connection.query(`select id,heroName,heroSkill,heroIcon from herolist where id=${id}`, function (error, results, fields) {
        if (!error) {
            res.send({
                code: 201,
                data: results[0]
            })
        } else {
            res.send({
                code: 500,
                msg: '获取失败，服务器错误'
            })
        }
    });
})
//4.2接收用户编辑的英雄数据
app.post("/hero/update",upload.single("heroIcon"),(req, res)=>{

    let { id,heroName, heroSkill } = req.body
    let heroIcon=''
     if(req.file){
    heroIcon = 'http://127.0.0.1:8089/uploads/' + req.file.filename
 
     }else{
     heroIcon=req.body.heroIconInput
}
if(!heroIcon){
    connection.query(`update herolist set heroName="${heroName}",heroSkill="${heroSkill}" where id=${id}`,(error,results,fields)=>{
        if(!error){
            res.send({
                code:201,
                msg:'更新成功'
            })
        }else{
            res.send({
                code:500,
                msg:'更新失败，服务器内部错误'
            })
        }
    })
    return
}
connection.query(`update herolist set heroName="${heroName}",heroSkill="${heroSkill}",heroIcon="${heroIcon}" where id=${id}`,(error,results,fields)=>{
    if(!error){
        res.send({
            code:201,
            msg:'更新成功'
        })
    }else{
        res.send({
            code:500,
            msg:'更新失败，服务器内部错误'
        })
    }
})
})

//5.生成验证码

var svgCaptcha = require('svg-captcha');
let  c
app.get('/captcha', function (req, res) {
    var captcha = svgCaptcha.create();
    c = captcha.text;    
    res.type('svg');
    res.status(200).send(captcha.data);
});

var urlencodedParser = bodyParser.urlencoded({ extended: false })
//6.注册接口
app.post('/hero/register',(req,res)=>{

    if(req.body.code.toLocaleLowerCase()!=c.toLocaleLowerCase()){
        res.send({
            code:200,
            msg:'验证码错误'
        })
        return
    }
    //将接收到的数据与数据库中的数据相比较
connection.query(`select username,password from user where username='${req.body.username}'`,(error,results,feilts)=>{
if(!error){
    if(results[0]){
          res.send({
              code:200,
              msg:'用户名已注册，请换一个'
               })
    }else{
        connection.query(`insert into user(username,password) values('${req.body.username}','${req.body.password}')`, function (error, results, fields) {
            if (!error) {
                res.send({
                    code: 201,
                    msg: '注册成功'
                })
            } else {
                res.send({
                    code: 500,
                    msg: '注册失败，服务器错误'
                })
            }
        });
    }
}else{
    res.send({
       code:500,
       msg:'服务器内部错误' 
    })
}
})
})



//创建服务器
app.listen(8089, () => {
    console.log('服务器已开，端口8089');
})